package util;

import java.sql.ResultSet;
import java.util.ArrayList;

import com.sun.jna.platform.win32.FlagEnum;

import util.crew.CCTV;
import util.crew.RenMinWang;
import util.crew.TouTiao;
import util.crew.XinHua;
import util.tool.Requests;
import util.tool.Sqlite3;
/**
 * 管控所有爬虫线程
 * @author kong
 *
 */
public class CentralControl {
	public static boolean run = false;
	String[] workKeyWordList = new String[]{"食品安全", "食品事故", "食品添加", "有毒有害食品", "食品违法"};
	Sqlite3 sql = new Sqlite3();
	Requests requests = new Requests();
	ArrayList<Thread> threads = new ArrayList<>();
	public CentralControl() {
		sql.openDb();
	}
	/**
	 * 开始爬取
	 */
	public void startCrew() {
		if (run) return;
		run=true;
		Thread thread;
		for (String string : workKeyWordList) {
			TouTiao t1 = new TouTiao(); t1.setInitData(requests, sql); t1.work(string); thread=new Thread(t1); threads.add(thread);
			CCTV t2 = new CCTV(); t2.setInitData(requests, sql); t2.work(string); thread=new Thread(t2); threads.add(thread);
			RenMinWang t3 = new RenMinWang(); t3.setInitData(requests, sql); t3.work(string); thread=new Thread(t3);threads.add(thread);
			XinHua t4 = new XinHua(); t4.setInitData(requests, sql); t4.work(string); thread=new Thread(t4);threads.add(thread);
		}
		int cnt = 0;
		for (Thread tCrew : threads) {
			tCrew.start();
			System.out.println(cnt);
			cnt++;
		}
	}
	/**
	 * 停止爬取
	 */
	public void stopCrew() {
		for (Thread t : threads) {
			if (t.isAlive())
				t.interrupt();
		}
		threads.clear();
		run=false;
	}
	/**
	 * 通过文章标题中的关键词获取数据库中数据
	 * @param keyWord 关键词
	 * @return 文章数组
	 */
	public ArrayList<News> getNewsByTitleKeyWord(String keyWord) {
		ArrayList<News> newsList = new ArrayList<>();
		try {
			ResultSet resultSet = sql.fetch("select * from data where title like '%%" + keyWord + "%%'");
			while (resultSet.next()) {
				newsList.add(new News(resultSet));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return newsList;
//		for (int i=0; i<newsList.size(); i++) {
//			System.out.println(newsList.get(i).getTitle());
//		}
	}
	/**
	 * 通过文章的内容关键词获取数据库中文章
	 * @param keyWord 关键词
	 * @return 新闻数组
	 */
	public ArrayList<News> getNewsByContentKeyWord(String keyWord) {
		ArrayList<News> newsList = new ArrayList<>();
		try {
			ResultSet resultSet = sql.fetch("select * from data where content like '%%" + keyWord + "%%'");
			while (resultSet.next()) {
				newsList.add(new News(resultSet));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return newsList;
	}
	/**
	 * 通过文章的标签获取数据库中文章
	 * @param keyWord 关键词
	 * @return 新闻列表
	 */
	public ArrayList<News> getNewsByTagsKeyWord(String keyWord) {
		ArrayList<News> newsList = new ArrayList<>();
		try {
			ResultSet resultSet = sql.fetch("select * from data where tags like '%%" + keyWord + "%%'");
			while (resultSet.next()) {
				newsList.add(new News(resultSet));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return newsList;
	}
	/**
	 * 通过来源获取数据库中文章
	 * @param keyWord 关键词
	 * @return 新闻数组
	 */
	public ArrayList<News> getNewsBySourceKeyWord(String keyWord) {
		ArrayList<News> newsList = new ArrayList<>();
		try {
			ResultSet resultSet = sql.fetch("select * from data where source like '%%" + keyWord + "%%'");
			while (resultSet.next()) {
				newsList.add(new News(resultSet));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return newsList;
	}
	/**
	 * 获取数据库中满足条件的所有文章
	 * @param colName 以数据库的colName列为搜索关键位，参数和util.News里的参数相同
	 * @param keyVal 查询的关键词
	 * @param dateOrder 时间：1:升序  0:降序  -1:初始状态，乱序
	 * @param timeLimit 0:24小时，1:7*24，2:30*24, -1 无限制
	 * @param platformLimit 指定平台：platformLimit[0]==true：头条，1：CCTV，2：人民网，3：新华网
	 * @return 获取到的新闻
	 */
	public ArrayList<News> get(String colName, String keyVal, int dateOrder, int timeLimit, boolean[] platformLimit) {
		ArrayList<News> newsList = new ArrayList<>();
		String sqlAsk = "select * from data where " + colName + " like '%%" + keyVal + "%%'";
		long pos = System.currentTimeMillis()/1000;
		if (timeLimit == 0) {
			pos -= 24 * 60 * 60;
		} else if (timeLimit == 1) {
			pos -= 7 * 24 * 60 * 60;
		} else if (timeLimit == 2) {
			pos -= 30 * 24 * 60 * 60;
		}
		if (timeLimit != -1) {
			sqlAsk += " and summitTime >'" + pos + "' ";
		}
		for (int i=0; i<4; i++) {
			if (platformLimit[i]) {
				if (colName != null || timeLimit != -1) {
					sqlAsk += " and (platform = ";			
				}
				else
					sqlAsk += " where (platform = ";
				for (int j=0; j<4; j++) {
					if (platformLimit[j]) {
						sqlAsk += (j+1) + " or ";
					}
				}
				sqlAsk = sqlAsk.substring(0, sqlAsk.length()-3);
				sqlAsk += ") ";
				break;
			}
		}
		if (dateOrder==1) {
			sqlAsk += " order by summitTime asc"; 
		} else if (dateOrder==0) {
			sqlAsk += " order by summitTime desc"; 
		}
		try {
			ResultSet resultSet = sql.fetch(sqlAsk);
			while (resultSet.next()) {
				newsList.add(new News(resultSet));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return newsList;
	}
	/**
	 * 提供翻页机制的查询
	 * @param colName 以数据库的colName列为搜索关键位，参数和util.News里的参数相同
	 * @param keyVal 查询的关键词
	 * @param dateOrder dateOrder 时间：1:升序  0:降序  -1:初始状态，乱序
	 * @param timeLimit timeLimit 0:24小时，1:7*24，2:30*24, -1 无限制
	 * @param platformLimit platformLimit 指定平台：platformLimit[0]==true：头条，1：CCTV，2：人民网，3：新华网
	 * @param pLimit 单页大小
	 * @param page 第几页
	 * @return 获取到的新闻数组
	 */
	public ArrayList<News> get(String colName, String keyVal, int dateOrder, int timeLimit, boolean[] platformLimit, int pLimit, int page) {
		ArrayList<News> newsList = new ArrayList<>();
		String sqlAsk = "select * from data where " + colName + " like '%%" + keyVal + "%%'";
		long pos = System.currentTimeMillis()/1000;
		if (timeLimit == 0) {
			pos -= 24 * 60 * 60;
		} else if (timeLimit == 1) {
			pos -= 7 * 24 * 60 * 60;
		} else if (timeLimit == 2) {
			pos -= 30 * 24 * 60 * 60;
		}
		if (timeLimit != -1) {
			sqlAsk += " and summitTime >'" + pos + "' ";
		}
		for (int i=0; i<4; i++) {
			if (platformLimit[i]) {
				if (colName != null || timeLimit != -1) {
					sqlAsk += " and platform = ";			
				}
				else
					sqlAsk += " where platform = ";
				for (int j=0; j<4; j++) {
					if (platformLimit[j]) {
						sqlAsk += (j+1) + " or ";
					}
				}
				sqlAsk = sqlAsk.substring(0, sqlAsk.length()-3);
				break;
			}
		}
		if (dateOrder==1) {
			sqlAsk += " order by summitTime asc"; 
		} else	if (dateOrder==0) {
			sqlAsk += " order by summitTime desc"; 
		}
		sqlAsk += " limit " + pLimit + " offset " + page;
		try {
			ResultSet resultSet = sql.fetch(sqlAsk);
			while (resultSet.next()) {
				newsList.add(new News(resultSet));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return newsList;
	}
}
